import * as Plotly from "plotly.js";

var historyData: Array<Plotly.Data> = [];
var layoutConfig: any = {
    xaxis: { scaleanchor: "y" }
};

function addData(xArr: Array<any>, yArr: Array<any>, pointText: Array<string>) {
    historyData.push({
        x: xArr,
        y: yArr,
        mode: "text+lines+markers",
        text: pointText,
        textinfo: "label",
        textposition: "bottom right",
    });
}

document.onpaste = (e) => {
    document.getElementById("myDiv").innerHTML = "";
    const text: string = e.clipboardData.getData("Text");
    const re = /x=((?:-?\d+)(?:\.\d+)?(?:e(?:-?\d+))?)(?:.*)y=((?:-?\d+)(?:\.\d+)?(?:e(?:-?\d+))?)/;

    let textArr: Array<string> = text.split("\n");

    var xArr = [];
    var yArr = [];
    var pointText: Array<string> = [];
    var indexNumber: number = 0;

    for (let i = 0; i < textArr.length; i++) {
        let v = textArr[i];
        const ptStr = re.exec(v);
        if (!ptStr) {
            if (xArr.length > 0) {
                addData(xArr, yArr, pointText);
                xArr = [];
                yArr = [];
                pointText = [];
            }
            continue;
        }
        const x = Number(ptStr[1]);
        const y = Number(ptStr[2]);
        if (x == NaN || y == NaN) {
            if (xArr.length > 0) {
                addData(xArr, yArr, pointText);
                xArr = [];
                yArr = [];
                pointText = [];
            }
            continue;
        }
        xArr.push(x);
        yArr.push(y);
        console.log(x, y);
        pointText.push(indexNumber.toString());
        indexNumber++;
    }
    if (xArr.length > 0) {
        addData(xArr, yArr, pointText);
    }

    Plotly.newPlot(
        "myDiv",
        historyData,
        layoutConfig
    );
};

document.getElementById("btn").onchange = (e) => {
    if (layoutConfig == undefined) {
        layoutConfig = {
            xaxis: { scaleanchor: "y" }
        }
    }
    else {
        layoutConfig = undefined
    }
    if (historyData.length == 0) {
        return;
    }

    Plotly.newPlot(
        "myDiv",
        historyData,
        layoutConfig
    );
}